//
//  PendingOrderController.m
//  DaiShengInvest
//
//  Created by 张睿 on 2017/7/4.
//  Copyright © 2017年 davinci. All rights reserved.
//

#import "PendingOrderController.h"
#import <SocketRocket.h>

@interface PendingOrderController ()<UITextFieldDelegate,SRWebSocketDelegate>

@property (nonatomic, strong)SRWebSocket * webSocket;

@property (nonatomic, weak)UIImageView * backImageView;

@property (nonatomic, strong)UITableView * tableView;

@property (nonatomic, weak)UIButton * payButton;

@property (nonatomic, strong) UIView *bgview;

@property (nonatomic, strong)UIDatePicker * datePicker;

@property (nonatomic, strong)UILabel * dateLabel;

@property (nonatomic, copy)NSString * showPullDownView;

@property (nonatomic, strong)UIView * backView;

@property (nonatomic, strong)UIButton * buyUpButton;

@property (nonatomic, strong)UIButton * buyDownButton;
@property (nonatomic, strong)UIButton * sellUpButton;

@property (nonatomic, strong)UIButton * sellDownButton;


@property (nonatomic, strong)UILabel * showPendingTypeLabel;
@property (nonatomic, strong)UIImageView * pendingTypeTextField;
@property (nonatomic, strong)UIButton * showTypeViewButton;
@property (nonatomic, strong)UILabel * pendingTypeLabel;
@property (nonatomic, strong)UILabel * pendingLabel;
@property (nonatomic, strong)UITextField * pendingTextField;
@property (nonatomic, strong)UILabel * countLabel;
@property (nonatomic, strong)UITextField * countTextField;
@property (nonatomic, strong)UILabel * stopLoseLabel;
@property (nonatomic, strong)UITextField * stopLoseTextField;
@property (nonatomic, strong)UILabel * stopWinLabel;
@property (nonatomic, strong)UITextField * stopWinTextField;
@property (nonatomic, strong)UIView * oneLineView;
@property (nonatomic, strong)UILabel * stopTimeLabel;
@property (nonatomic, strong)UIImageView * rightImageView;
@property (nonatomic, strong)UIView * twoLineView;
@property (nonatomic, strong)UIButton * showPickerViewButton;


@property (nonatomic, weak)UILabel * priceLabel;

@end

@implementation PendingOrderController


- (void)viewDidLoad {
    
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self loadData];
    [self setupNSNoti];
    [self setupNavBar];
    [self setupUI];
}

- (void)loadData{
    
    _webSocket.delegate = nil;
    [_webSocket close];
    
    _webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"ws://103.20.249.35:9506"]]];
    [_webSocket setDelegateOperationQueue:[NSOperationQueue mainQueue]];
    
    _webSocket.delegate = self;

    
    [_webSocket open];
}


- (void)webSocketDidOpen:(SRWebSocket *)webSocket;
{
    NSLog(@"Websocket Connected");
    
}

- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;
{
    NSLog(@":( Websocket Failed With Error %@", error);
    
    _webSocket = nil;
}


- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message;
{
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    NSData *jsonData = [message dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    
    NSArray * array = dic[@"quote"];
    
    for (NSDictionary * productInfoDict in array) {
        
        NSString * name = [NSString stringWithFormat:@"%@",productInfoDict[@"symbol"]];
        
        if ([self.productID isEqualToString:name]) {
            
            NSString * bid = [NSString stringWithFormat:@"%@",productInfoDict[@"bid"]];
            float  bidFloat = [bid floatValue];
            NSString * ask = [NSString stringWithFormat:@"%@",productInfoDict[@"ask"]];
            float askFloat = [ask floatValue];
            
            NSArray * bidArray = [bid componentsSeparatedByString:@"."];
            NSArray * askArray = [ask componentsSeparatedByString:@"."];
            
            NSString * firstBid = bidArray.firstObject;
            NSString * firstAsk = askArray.firstObject;
            
            NSInteger  bidLength = [firstBid length] + 1;
            NSInteger askLength = [firstAsk length] + 1;
            
            double bida = pow(0.1, bidLength) * 10;
            float bidb = bidFloat - bida;
            
            double aska = pow(0.1, askLength) * 10;
            float askb = askFloat + aska;
            
            NSString * bidRel = [NSString stringWithFormat:@"%.5f",bidb];
            NSString * askRel = [NSString stringWithFormat:@"%.5f",askb];
            
//            if (bid.length <= 7) {
//                bidRel = bid;
//            }else{
//                bid = [bid substringToIndex:8];
//                bidRel = bid;
//            }
//            
//            if (ask.length <= 7) {
//                askRel = ask;
//            }else{
//                ask = [ask substringToIndex:8];
//                askRel = ask;
//            }
            
            self.priceLabel.text = [NSString stringWithFormat:@"价格(<=%@ 或 >= %@)",bidRel,askRel];
        }
    }
}



- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;
{
    NSLog(@"==WebSocket closed");
}

- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload;
{
    NSLog(@"Websocket received pong");
}

- (void)setupNavBar{
    
    self.title = @"挂单";
    
    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(15 * SCREENH6, 5 * SCREENH6, 12 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"1返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToAccountView) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
}



- (void)setupNSNoti{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didShowViewButtonOnCell) name:@"didShowViewButton" object:nil];
    
    
}



- (void)setupUI{
    
//    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    UIImageView * backImage = [[UIImageView alloc] init];
    
    backImage.image = [UIImage imageNamed:@"背景"];
    
    self.backImageView = backImage;
    
    [self.view addSubview:self.backImageView];
    
    
    self.showPendingTypeLabel = [self setupLabel:@"挂单类型"];
    
    [self.view addSubview:self.showPendingTypeLabel];
    
    self.pendingTypeTextField = [UIImageView new];
    
    self.pendingTypeTextField.image = [UIImage imageNamed:@"买涨"];
    self.pendingTypeTextField.contentMode = UIViewContentModeScaleAspectFill;
    self.pendingTypeTextField.userInteractionEnabled = YES;
    
    [self.view addSubview:self.pendingTypeTextField];
    
    self.showTypeViewButton = [UIButton new];
    
    self.showTypeViewButton.backgroundColor = [UIColor clearColor];
    [self.showTypeViewButton addTarget:self action:@selector(didShowViewButtonOnCell) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.showTypeViewButton];
    
    self.pendingTypeLabel = [self setupLabel:@"未设置"];
    
    [self.pendingTypeTextField addSubview:self.pendingTypeLabel];
    
    self.pendingLabel = [self setupLabel:@"价格"];
    
    [self.view addSubview:self.pendingLabel];
    
//    self.pendingTextField = [self setupTextField:@"价格" ];
    self.pendingTextField = [self setupTextField:@"价格" withTextName:self.nowPrice];
    
    [self.view addSubview:self.pendingTextField];
    
    UILabel * priceLabel = [UILabel new];
    
    priceLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:13 * SCREENH6];
    priceLabel.textColor = ColorWithRGB(0xa2a2a2);
    priceLabel.textAlignment = NSTextAlignmentCenter;
    priceLabel.text = @"";
    
    self.priceLabel = priceLabel;
    
    [self.view addSubview:self.priceLabel];
    
    self.countLabel = [self setupLabel:@"手数"];
    
    [self.view addSubview:self.countLabel];
    
//    self.countTextField = [self setupTextField:@"价格"];
    self.countTextField = [self setupTextField:@"价格" withTextName:@"0.01"];
    
    [self.view addSubview:self.countTextField];
    
    self.stopLoseLabel = [self setupLabel:@"止损点数"];
    
    [self.view addSubview:self.stopLoseLabel];
    
//    self.stopLoseTextField = [self setupTextField:@"价格"];
    self.stopLoseTextField = [self setupTextField:@"价格" withTextName:@""];
    
    [self.view addSubview:self.stopLoseTextField];
    
    self.stopWinLabel = [self setupLabel:@"止盈点数"];
    
    [self.view addSubview:self.stopWinLabel];
    
//    self.stopWinTextField = [self setupTextField:@"价格"];
    self.stopWinTextField = [self setupTextField:@"价格" withTextName:@""];
    
    [self.view addSubview:self.stopWinTextField];
    
    self.oneLineView = [UIView new];
    
    self.oneLineView.backgroundColor = [UIColor whiteColor];
    self.oneLineView.alpha = 0.05;
    
    [self.view addSubview:self.oneLineView];
    
    self.stopTimeLabel = [self setupLabel:@"截止时间"];
    
    [self.view addSubview:self.stopTimeLabel];
    
    self.twoLineView = [UIView new];
    
    self.twoLineView.backgroundColor = [UIColor whiteColor];
    self.twoLineView.alpha = 0.05;
    
    [self.view addSubview:self.twoLineView];
    
    
    self.rightImageView = [UIImageView new];
    
    self.rightImageView.image = [UIImage imageNamed:@"修改头像"];
    self.rightImageView.userInteractionEnabled = YES;
    
    [self.view addSubview:self.rightImageView];
    
    self.showPickerViewButton = [UIButton new];
    
    self.showPickerViewButton.backgroundColor = [UIColor clearColor];
    [self.showPickerViewButton addTarget:self action:@selector(setupDatePivkerView) forControlEvents:UIControlEventTouchUpInside];
    self.showPickerViewButton.selected = NO;
    
    [self.view addSubview:self.showPickerViewButton];
    
    self.dateLabel = [[UILabel alloc] init];//WithFrame:CGRectMake(195 * SCREENH6, 497 * SCREENH6, 150 * SCREENH6, 20 * SCREENH6)];
    
    self.dateLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    self.dateLabel.textColor = ColorWithRGB(0xeeeeee);
    self.dateLabel.text = @"未设置";
//    self.dateLabel.hidden = YES;
    
    [self.view addSubview:self.dateLabel];
    
    [self.dateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).offset(497 * SCREENH6);
        make.trailing.mas_equalTo(self.view).offset(-40 * SCREENH6);
    }];
    
    
    UIButton * payButton = [[UIButton alloc] initWithFrame:CGRectMake(15 * SCREENH6, 585 * SCREENH6, 345 * SCREENH6, 45 * SCREENH6)];
    
    [payButton setTitle:@"下单" forState:UIControlStateNormal];
    payButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:16 * SCREENH6];//
    [payButton setBackgroundImage:[UIImage imageNamed:@"注册"] forState:UIControlStateNormal];
    payButton.layer.borderColor = [[UIColor blackColor] CGColor];
    //边框宽度
    //    saveButton.layer.borderWidth =1.0f;
    //处理圆角
    payButton.layer.cornerRadius =5.0f;
    [payButton setTitleColor:ColorWithRGB(0xffffff) forState:UIControlStateNormal];
    [payButton addTarget:self action:@selector(didPayButton) forControlEvents:UIControlEventTouchUpInside];
    
    self.payButton = payButton;
    
    [self.view addSubview:self.payButton];
    
}



- (void)viewDidLayoutSubviews{
    
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.bottom.mas_equalTo(self.view);
    }];
    
    
    [self.showPendingTypeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(15 * SCREENH6);
        make.top.mas_equalTo(self.view).offset(100 * SCREENH6);
    }];
    
    [self.pendingTypeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(90 * SCREENH6);
        make.centerY.mas_equalTo(self.showPendingTypeLabel);
        make.trailing.mas_equalTo(self.view).offset(-15 * SCREENH6);
        make.height.mas_equalTo(40 * SCREENH6);
    }];
    
    [self.pendingTypeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.pendingTypeTextField);
        make.centerX.mas_equalTo(self.pendingTypeTextField);
    }];
    
    [self.showTypeViewButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.bottom.top.mas_equalTo(self.pendingTypeTextField);
        make.height.width.mas_equalTo(40 * SCREENH6);
    }];
    
    [self.pendingTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.pendingTypeTextField.mas_bottom).offset(34 * SCREENH6);
        make.leading.trailing.height.mas_equalTo(self.pendingTypeTextField);
    }];
    
    [self.priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.pendingTextField.mas_bottom).offset(5 * SCREENH6);
    }];
    
    [self.pendingLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.showPendingTypeLabel);
        make.centerY.mas_equalTo(self.pendingTextField);
    }];
    
    [self.countTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.pendingTextField.mas_bottom).offset(55 * SCREENH6);
        make.leading.trailing.height.mas_equalTo(self.pendingTextField);
    }];
    
    [self.countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.pendingLabel);
        make.centerY.mas_equalTo(self.countTextField);
    }];
    
    [self.stopLoseTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.countTextField.mas_bottom).offset(34 * SCREENH6);
        make.leading.trailing.height.mas_equalTo(self.countTextField);
    }];
    
    [self.stopLoseLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.countLabel);
        make.centerY.mas_equalTo(self.stopLoseTextField);
    }];
    
    [self.stopWinTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.stopLoseTextField.mas_bottom).offset(34 * SCREENH6);
        make.leading.trailing.height.mas_equalTo(self.stopLoseTextField);
    }];
    
    [self.stopWinLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.stopLoseLabel);
        make.centerY.mas_equalTo(self.stopWinTextField);
    }];
    
    [self.oneLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.view);
        make.height.mas_equalTo(1 * SCREENH6);
        make.top.mas_equalTo(self.stopWinTextField.mas_bottom).offset(28 * SCREENH6);
    }];
    
    [self.stopTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.stopWinLabel);
        make.top.mas_equalTo(self.oneLineView.mas_bottom).offset(20 * SCREENH6);
    }];
    
    [self.twoLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.height.mas_equalTo(self.oneLineView);
        make.top.mas_equalTo(self.oneLineView.mas_bottom).offset(60 * SCREENH6);
    }];
    
    [self.rightImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.stopTimeLabel);
        make.trailing.mas_equalTo(self.view).offset(-15 * SCREENH6);
    }];
    
    [self.showPickerViewButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.oneLineView.mas_bottom);
        make.bottom.mas_equalTo(self.twoLineView.mas_top);
        make.leading.trailing.mas_equalTo(self.stopWinTextField);
    }];
}

- (void)setupDatePivkerView{
    
    if (!self.showPickerViewButton.selected) {
       
        self.bgview = [[UIView alloc]init];
        self.bgview.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, SCREENH_HEIGHT / 3);
        self.bgview.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:self.bgview];
        
        UIView *btnView = [[UIView alloc]init];
        btnView.frame = CGRectMake(0, 0, self.view.frame.size.width, 40 * SCREENH6);
        btnView.backgroundColor = [UIColor lightGrayColor];
        [self.bgview addSubview:btnView];
        
        UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        sureBtn.frame = CGRectMake(10 * SCREENH6, 5 * SCREENH6, 60 * SCREENH6, 30 * SCREENH6);
        [sureBtn setTitle:@"取消" forState:UIControlStateNormal];
        [sureBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [sureBtn addTarget:self action:@selector(cancelBtn) forControlEvents:UIControlEventTouchUpInside];
        [btnView addSubview:sureBtn];
        
        UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        cancelBtn.frame = CGRectMake(self.view.frame.size.width - 70 * SCREENH6, 5 * SCREENH6, 60 * SCREENH6, 30 * SCREENH6);
        [cancelBtn setTitle:@"确定" forState:UIControlStateNormal];
        [cancelBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [cancelBtn addTarget:self action:@selector(sureBtn) forControlEvents:UIControlEventTouchUpInside];
        [btnView addSubview:cancelBtn];
        
        self.datePicker = [[UIDatePicker alloc] init];
        //自定义位置
        self.datePicker.frame = CGRectMake(0, 40 * SCREENH6, SCREEN_WIDTH, 210 * SCREENH6);
        //设置背景颜色
        self.datePicker.backgroundColor = [UIColor whiteColor];
        //datePicker.center = self.center;
        //设置本地化支持的语言（在此是中文)
        self.datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh"];
        //显示方式是只显示年月日
        self.datePicker.datePickerMode = UIDatePickerModeDateAndTime;
        //放在盖板上
        [self.bgview addSubview:self.datePicker];
        
        [UIView animateWithDuration:0.3 animations:^{
            self.bgview.frame = CGRectMake(0, SCREENH_HEIGHT - SCREENH_HEIGHT / 3, SCREEN_WIDTH, SCREENH_HEIGHT / 3);
        }];
        
        self.showPickerViewButton.selected = YES;
    }else{
        
        self.showPickerViewButton.selected = NO;
    }
    
    
    
    
}


- (void)sureBtn{
    
    [UIView animateWithDuration:0.5 animations:^{
        self.bgview.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, SCREENH_HEIGHT / 3);
    } completion:^(BOOL finished) {
    }];
    
//    NSString * address = [NSString stringWithFormat:@"%@ %@", self.arrayDS[_provinceIndex][@"province"], self.arrayDS[_provinceIndex][@"citys"][_cityIndex][@"city"]];
//    
//    self.sureCityLabel.text = address;
    
    NSDate *date = self.datePicker.date;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString  *string = [[NSString alloc]init];
    string = [dateFormatter stringFromDate:date];
    
//    self.title = string;
    self.dateLabel.hidden = NO;
    self.dateLabel.text = string;
    
    self.showPickerViewButton.selected = NO;
}



- (void)cancelBtn{
    
    [UIView animateWithDuration:0.5 animations:^{
        self.bgview.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, SCREENH_HEIGHT / 3);
    } completion:^(BOOL finished) {
    }];
    
    self.showPickerViewButton.selected = NO;
    
}



//点击下单
- (void)didPayButton{
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSString * buyType;
    
    if ([self.pendingTypeLabel.text isEqualToString:@"止盈买入"]) {
        buyType = @"buy,limit";
    }else if ([self.pendingTypeLabel.text isEqualToString:@"止损买入"]){
        buyType = @"buy,stop";
    }else if ([self.pendingTypeLabel.text isEqualToString:@"止盈卖出"]){
        buyType = @"sell,limit";
    }else if([self.pendingTypeLabel.text isEqualToString:@"止损卖出"]){
        buyType = @"sell,stop";
    }else{
        buyType = @"";
    }

    NSString * dateString;
    
    if ([self.dateLabel.text isEqualToString:@"未设置"]) {
        dateString = @"";
    }else{
        
        NSArray *array = [self.dateLabel.text componentsSeparatedByString:@" "]; //从字符A中分隔成2个元素的数组
        dateString = [NSString stringWithFormat:@"%@T%@Z",array.firstObject,array.lastObject];
    }
    
    float relStopLoss = 0;
    float relStopWin = 0;
    float orderPrice = [self.pendingTextField.text floatValue];
    
    
//    if ([self.stopWinTextField.text isEqualToString:@""] || [self.stopLoseTextField.text isEqualToString:@""]) {
//        
//    }else{
//        
//        
//        float stopLoss = [self.stopLoseTextField.text floatValue];
//        float stopWin = [self.stopWinTextField.text floatValue];
//        
//        NSArray * bidArray = [self.pendingTextField.text componentsSeparatedByString:@"."];
//        
//        NSString * firstBid = bidArray.firstObject;
//        
//        NSInteger  bidLength = [firstBid length];
//        
//        double stopLossa = pow(0.1, bidLength) * stopLoss;
//        double stopWina = pow(0.1, bidLength) * stopWin;
//        
//        if ([buyType isEqualToString:@"buy,limit"] || [buyType isEqualToString:@"buy,stop"]) {
//            
//            relStopLoss = orderPrice - stopLossa;
//            relStopWin = orderPrice + stopWina;
//        }else{
//            
//            relStopLoss = orderPrice + stopLossa;
//            relStopWin = orderPrice - stopWina;
//        }
//        
//    }
    
    
    if ([self.stopWinTextField.text isEqualToString:@""] && [self.stopLoseTextField.text isEqualToString:@""]) {
        
    }else if ([self.stopWinTextField.text isEqualToString:@""]){
        
        float stopLose = [self.stopLoseTextField.text floatValue];
        
        NSArray * bidArray = [self.pendingTextField.text componentsSeparatedByString:@"."];
        
        NSString * firstBid = bidArray.firstObject;
        
        NSInteger  bidLength = [firstBid length];
        double stopLossa = pow(0.1, 5 -bidLength) * stopLose;
        
        if ([buyType isEqualToString:@"buy,limit"] || [buyType isEqualToString:@"buy,stop"]) {
            
            relStopLoss = orderPrice - stopLossa;
            
        }else{
            relStopLoss = orderPrice + stopLossa;
            
        }}else if ([self.stopLoseTextField.text isEqualToString:@""]){
            
            float stopLose = [self.stopWinTextField.text floatValue];
            
            NSArray * bidArray = [self.pendingTextField.text componentsSeparatedByString:@"."];
            
            NSString * firstBid = bidArray.firstObject;
            
            NSInteger  bidLength = [firstBid length];
            double stopLossa = pow(0.1, 5 - bidLength) * stopLose;
            
            if ([buyType isEqualToString:@"buy,limit"] || [buyType isEqualToString:@"buy,stop"]) {
                
                relStopWin = orderPrice - stopLossa;
                
            }else{
                relStopWin = orderPrice + stopLossa;
                
            }
        }else {
            
            float stopLoss = [self.stopLoseTextField.text floatValue];
            float stopWin = [self.stopWinTextField.text floatValue];
            
            NSArray * bidArray = [self.pendingTextField.text componentsSeparatedByString:@"."];
            
            NSString * firstBid = bidArray.firstObject;
            
            NSInteger  bidLength = [firstBid length];
            
            double stopLossa = pow(0.1, 5 - bidLength) * stopLoss;
            double stopWina = pow(0.1, 5 - bidLength) * stopWin;
            
            if ([buyType isEqualToString:@"buy,limit"] || [buyType isEqualToString:@"buy,stop"]) {
                
                relStopLoss = orderPrice - stopLossa;
                relStopWin = orderPrice + stopWina;
            }else{
                
                relStopLoss = orderPrice + stopLossa;
                relStopWin = orderPrice - stopWina;
            }
        }
    
    
    NSString * stopLose = [NSString stringWithFormat:@"%.4f",relStopLoss];
    NSString * stopWinString = [NSString stringWithFormat:@"%.4f",relStopWin];
    
    NSDictionary * parametersDic = @{@"symbol":self.productID,@"volume":self.countTextField.text,@"price":self.pendingTextField.text,@"orderType":buyType,@"stopLoss":stopLose,@"takeProfit":stopWinString,@"expirationDate":dateString};
    
    [[NetworkTool sharedTools] POST:@"symbols/orders" parameters:parametersDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        NSString * code = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        
        if ([code isEqualToString:@"0"]) {
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"恭喜你，交易成功！"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      //响应事件
                                                                      [self.navigationController popViewControllerAnimated:YES];
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
            
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseObject[@"msg"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      //响应事件
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"服务器内部错误，请重试。"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  //响应事件
                                                                 
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }];
    
}



//出现挂单类型弹窗
- (void)didShowViewButtonOnCell{
    
    self.backView = [[UIView alloc] initWithFrame:CGRectMake(90 * SCREENH6, 130 * SCREENH6, 270 * SCREENH6, 160 * SCREENH6)];
    
    self.backView.layer.borderWidth = 1 * SCREENH6;
    self.backView.layer.cornerRadius =5.0f;
    self.backView.layer.borderColor = [ColorWithRGB(0x3c5059) CGColor];
    self.backView.backgroundColor = ColorWithRGB(0x0c2029);
    
    [self.view addSubview:self.backView];
    
    UIView * lineView = [UIView new];
    
    lineView.backgroundColor = ColorWithRGB(0x3c5059);
    
    [self.backView addSubview:lineView];
    
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.backView);
        make.top.mas_equalTo(self.backView).offset(39.5 * SCREENH6);
        make.height.mas_equalTo(1 * SCREENH6);
    }];
    
    self.buyUpButton = [UIButton new];
    
    self.buyUpButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:16 * SCREENH6];
    [self.buyUpButton setTitleColor:ColorWithRGB(0xeeeeee) forState:UIControlStateNormal];
    [self.buyUpButton setTitle:@"止盈买入" forState:UIControlStateNormal];
    [self.buyUpButton addTarget:self action:@selector(didBuyUpDownButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.backView addSubview:self.buyUpButton];
    
    [self.buyUpButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.backView);
        make.top.mas_equalTo(self.backView).offset(4.5 * SCREENH6);
    }];
    
    
    self.buyDownButton = [UIButton new];
    
    self.buyDownButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:16 * SCREENH6];
    [self.buyDownButton setTitleColor:ColorWithRGB(0xeeeeee) forState:UIControlStateNormal];
    [self.buyDownButton setTitle:@"止损买入" forState:UIControlStateNormal];
    [self.buyDownButton addTarget:self action:@selector(didBuyUpDownButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.backView addSubview:self.buyDownButton];
    
    [self.buyDownButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.backView);
        make.top.mas_equalTo(lineView.mas_bottom).offset(2.5 * SCREENH6);
    }];
    
    
    UIView * lineOneView = [UIView new];
    
    lineOneView.backgroundColor = ColorWithRGB(0x3c5059);
    
    [self.backView addSubview:lineOneView];
    
    [lineOneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.height.mas_equalTo(lineView);
        make.top.mas_equalTo(self.buyDownButton.mas_bottom).offset(2 * SCREENH6);
    }];
    
    
    self.sellUpButton = [UIButton new];
    
    self.sellUpButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:16 * SCREENH6];
    [self.sellUpButton setTitleColor:ColorWithRGB(0xeeeeee) forState:UIControlStateNormal];
    [self.sellUpButton setTitle:@"止盈卖出" forState:UIControlStateNormal];
    [self.sellUpButton addTarget:self action:@selector(didBuyUpDownButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.backView addSubview:self.sellUpButton];
    
    [self.sellUpButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.backView);
        make.top.mas_equalTo(lineOneView.mas_bottom).offset(2.5 * SCREENH6);
    }];
    
    
    UIView * lineTwoView = [UIView new];
    
    lineTwoView.backgroundColor = ColorWithRGB(0x3c5059);
    
    [self.backView addSubview:lineTwoView];
    
    [lineTwoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.height.mas_equalTo(lineOneView);
        make.top.mas_equalTo(self.sellUpButton.mas_bottom).offset(2.5 * SCREENH6);
    }];
    
    
    self.sellDownButton = [UIButton new];
    
    self.sellDownButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:16 * SCREENH6];
    [self.sellDownButton setTitleColor:ColorWithRGB(0xeeeeee) forState:UIControlStateNormal];
    [self.sellDownButton setTitle:@"止损卖出" forState:UIControlStateNormal];
    [self.sellDownButton addTarget:self action:@selector(didBuyUpDownButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.backView addSubview:self.sellDownButton];
    
    [self.sellDownButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.backView);
        make.bottom.mas_equalTo(self.backView).offset(-4 * SCREENH6);
    }];
}


- (void)didBuyUpDownButton:(UIButton *)button{
    
    if (button == self.buyUpButton) {
        
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeUp" object:nil];
        self.pendingTypeLabel.text = @"止盈买入";

    }else if(button == self.buyDownButton){
        
        self.pendingTypeLabel.text = @"止损买入";
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeDown" object:nil];
        
    }else if(button == self.sellUpButton){
        
        self.pendingTypeLabel.text = @"止盈卖出";
        //        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeDown" object:nil];
        
    }else{
        self.pendingTypeLabel.text = @"止损卖出";
    }
    
    [self.backView removeFromSuperview];
}



- (UILabel *)setupLabel:(NSString *)string{
    
    UILabel * label = [UILabel new];
    
    label.font = [UIFont fontWithName:@"PingFangSC-Medium" size:15 * SCREENH6];
    label.textColor = ColorWithRGB(0xffffff);
    label.text = string;
    
    return label;
}


- (UITextField *)setupTextField:(NSString *)name withTextName:(NSString *)textString{
    
    
    UITextField * textFiled = [[UITextField alloc] init];
    
    textFiled.borderStyle = UITextBorderStyleNone;
    textFiled.backgroundColor = [UIColor clearColor];
    textFiled.delegate = self;
    
    textFiled.background = [UIImage imageNamed:name];
    textFiled.textAlignment = UITextAlignmentCenter;
    
    if ([textString isEqualToString:@""]) {
        
        NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
        attrs[NSForegroundColorAttributeName] = ColorWithRGB(0xa2a2a2);
        attrs[NSFontAttributeName] = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
        textFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"未设置" attributes:attrs];
    }
    

    textFiled.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    textFiled.textColor = ColorWithRGB(0xeeeeee);
    textFiled.text = textString;
    
    
    UIButton * reduceButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40 * SCREENH6, 40 * SCREENH6)];
    
    reduceButton.backgroundColor = [UIColor clearColor];
    [reduceButton addTarget:self action:@selector(didReduceButton:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [textFiled addSubview:reduceButton];
    
    textFiled.leftView = reduceButton;
    textFiled.leftViewMode = UITextFieldViewModeAlways;
    
    
    UIButton * addButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40 * SCREENH6, 40 * SCREENH6)];
    
    addButton.backgroundColor = [UIColor clearColor];
    [addButton addTarget:self action:@selector(didAddButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [textFiled addSubview:addButton];
    
    textFiled.rightView = addButton;
    textFiled.rightViewMode = UITextFieldViewModeAlways;
    
    textFiled.keyboardType = UIKeyboardTypeDecimalPad;
    textFiled.keyboardAppearance = UIKeyboardAppearanceDark;
    
    
    return textFiled;
}

//点击减少按钮
- (void)didReduceButton:(UIButton *)button{
    //字符串转数字   --
    //    float floatString = [newString floatValue];
    if (button.superview == self.pendingTextField) {
        
        float floatString = [self.pendingTextField.text floatValue];
         float newFloat = 0;
        
        if (floatString <= 0.0001) {
            newFloat = 0.0001;
        }else{
            newFloat = floatString - 0.0001;
        }

        
        NSString *stringFloat = [NSString stringWithFormat:@"%.4f",newFloat];
        
        self.pendingTextField.text = stringFloat;
        
    }else if (button.superview == self.countTextField){
        
        float floatString = [self.countTextField.text floatValue];
        float newFloat = 0;
        
        if (floatString <= 0.01) {
            newFloat = 0.01;
        }else{
           newFloat = floatString - 0.01;
        }
        
        NSString *stringFloat = [NSString stringWithFormat:@"%.2f",newFloat];
        
        self.countTextField.text = stringFloat;
        
    }else if (button.superview == self.stopLoseTextField){
        
        if ([self.stopLoseTextField.text isEqualToString:@""]) {
            
            return;
        }else{
            
            int floatString = [self.stopLoseTextField.text intValue];
            
            int newFloat = floatString;
            
            if (newFloat == 10) {
                
                newFloat = 10;
                
                [self showAlertView];
            }else{
                
                newFloat --;
            }
            
            NSString *stringFloat = [NSString stringWithFormat:@"%d",newFloat];
            
            self.stopLoseTextField.text = stringFloat;
        }
        
        
    }else{
        
        if ([self.stopWinTextField.text isEqualToString:@""]) {
            
            return;
        }else{
            
            int floatString = [self.stopWinTextField.text floatValue];
            
            int newFloat = floatString;
            
            if (newFloat == 10) {
                
                newFloat = 10;
                
                [self showAlertView];
            }else{
                
                newFloat --;
            }
            
            NSString *stringFloat = [NSString stringWithFormat:@"%d",newFloat];
            
            self.stopWinTextField.text = stringFloat;
        }
    }
}


//点击添加按钮
- (void)didAddButton:(UIButton *)button{
    
    if (button.superview == self.pendingTextField) {
        
        float floatString = [self.pendingTextField.text floatValue];
        
        float newFloat = floatString + 0.0001;
        
        NSString *stringFloat = [NSString stringWithFormat:@"%.4f",newFloat];
        
        self.pendingTextField.text = stringFloat;
        
    }else if (button.superview == self.countTextField){
        
        float floatString = [self.countTextField.text floatValue];
        
        float newFloat = floatString + 0.01;
        
        NSString *stringFloat = [NSString stringWithFormat:@"%.2f",newFloat];
        
        self.countTextField.text = stringFloat;
        
    }else if (button.superview == self.stopLoseTextField){
        
        if ([self.stopLoseTextField.text isEqualToString:@""]) {
            
            self.stopLoseTextField.text = @"10";
        }else{
            
            int floatString = [self.stopLoseTextField.text intValue];
            
            int newFloat = floatString + 1;
            
            NSString *stringFloat = [NSString stringWithFormat:@"%d",newFloat];
            
            self.stopLoseTextField.text = stringFloat;
        }
        
        
    }else{
        
        if ([self.stopWinTextField.text isEqualToString:@""]) {
            
            self.stopWinTextField.text = @"10";
        }else{
            
            int floatString = [self.stopWinTextField.text intValue];
            
            int newFloat = floatString + 1;
            
            NSString *stringFloat = [NSString stringWithFormat:@"%d",newFloat];
            
            self.stopWinTextField.text = stringFloat;
        }
    }

}


- (void)backToAccountView{
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.pendingTextField resignFirstResponder];
    [self.countTextField resignFirstResponder];
    [self.stopLoseTextField resignFirstResponder];
    [self.stopWinTextField resignFirstResponder];
    
    [self.backView removeFromSuperview];
}


- (void)showAlertView{
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                   message:@"点数必须大于等于10"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                          handler:^(UIAlertAction * action) {
                                                              //响应事件
//                                                              NSLog(@"action = %@", action);
                                                          }];
    
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
    
}


- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    if (textField == self.stopLoseTextField || textField == self.stopWinTextField) {
        
        if ([textField.text isEqualToString:@""]) {
            
        }else{
            
            int count = [textField.text intValue];
            
            if (count < 10) {
                
                textField.text = @"";
                
                [self showAlertView];
            }
        }
    }
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
